﻿using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Exhort.Backstage.Components;
using Exhort.Utility.Entities;
using Exhort.Utility.Helper;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;

namespace Exhort.Backstage.Areas.Other.Controllers
{
    [Area("Other")]
    public class CommonController : WorkController
    {
        public string Cut(string dir, int width, int height)
        {
            var temp = $"{ConfigHelper.RootPath}/wwwroot/userfiles/temp/";
            var path = $"{ConfigHelper.RootPath}/wwwroot/userfiles/{dir}/";

            if (!Directory.Exists(temp)) { Directory.CreateDirectory(temp); }
            if (!Directory.Exists(path)) { Directory.CreateDirectory(path); }

            if (Request.Form.Files.Count > 0)
            {
                try
                {
                    IFormFile file = Request.Form.Files[0];
                    string fileExt = Path.GetExtension(file.FileName).ToLower();
                    string tempFile = $"{temp}{Guid.NewGuid()}{fileExt}";
                    string fileName = DateTime.Now.ToString("yyyyMMddHHmmss_ffff", DateTimeFormatInfo.InvariantInfo) + fileExt;

                    using (var fs = new FileStream(tempFile, FileMode.Create))
                    {
                        file.CopyTo(fs);
                    }

                    ThumbnailHelper.Generate(tempFile, path + fileName, width, height, TnType.Cut);

                    System.IO.File.Delete(tempFile);

                    return ServiceResult.Success(data: new { file = fileName }).Serialize();
                }
                catch (Exception ex)
                {
                    LogHelper.Error(this, ex); throw ex;
                }
            }
            else { throw new Exception("未找到文件！"); }
        }
    }
}